<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * AbstractController
 * 
 * @package Seowebd : Medic - Online
 * @author Seowebd
 * @copyright 2014
 * @version $Id$
 * @access public
 */
abstract class AbstractController extends CI_Controller 
{
    public static $mimeTypes = array();
    protected static $configurations = array();
    
    public function __construct($request = null)
    {
        parent::__construct();
        
        // Init libraries and model
        //$this->load->library('session');
        $this->load->library('Tools');
        $this->load->helper('url');
        $this->load->model('ORM/System/SystemConfigsORM');
        $this->load->model('Metier/System/TranslateMetier');
        
        // Setting up the current lang
        $this->settingUpLang();
        
        // Setting up filter for a list
        $this->settingUpFilter();
        
        // Setting up sorting for a list
        $this->settingUpSorting();
    }
    
    public function getConfig ($key = NULL)
    {
        // Initialized all configuration
        if (empty(self::$configurations)) {
            foreach ($this->SystemConfigsORM->getAll() AS $row)
            self::$configurations[$row->name] = $row;
        }
        
        if ($key === NULL) {
            return self::$configurations;
        } elseif (isset(self::$configurations[$key]->value)) {
            return self::$configurations[$key]->value;
        }
        return NULL;
    }
    
    protected function settingUpLang () 
    {
        $languages = array_keys(NZ_Config::$languages);
        // Get current lang from query
        $defaultLang = $this->input->get_post('set_lang');
        
        // Get current lang from session
        if (!in_array($defaultLang, $languages)) {
            $defaultLang = $this->session->userdata('lang');
        }
        
        // Get default lang from DB
        if (!in_array($defaultLang, $languages)) {
            $defaultLang = $this->getConfig('defaultLang');
        }
        
        // Get default lang from config.php
        if (!in_array($defaultLang, $languages)) {
            $defaultLang = $this->config->item('default_lang');
        }
        
        // Get default lang from NZ_Config
        if (!in_array($defaultLang, $languages)) {
            $defaultLang = NZ_Config::$defaultLang;
        }
        
        // Otherwise default lang is en
        if (!in_array($defaultLang, $languages)) {
            $defaultLang = 'en';
        }
        
        // Set the current language
        $this->session->set_userdata('lang', $defaultLang);
    }
    
    protected function settingUpFilter () 
    {
        if ($this->input->get_post('filter_reset')) {
            $this->session->unset_userdata('filter');
        } else {
            // Get configs from query
            $filter = array(
                'filter_by' => $this->input->get_post('filter_by'),
                'filter_val' => $this->input->get_post('filter_val'),
            );
            
            // Get configs from session
            if (empty($filter['filter_by']) || empty($filter['filter_val'])) {
                $filter = $this->session->userdata('filter');
            }
            
            if (empty($filter['filter_by']) || empty($filter['filter_val'])) {
                // Reset configs
                $this->session->unset_userdata('filter');
            } else {
                // Enable configs
                $this->session->set_userdata('filter', $filter);
            }
        }
    }
    
    protected function settingUpSorting () 
    {
        if ($this->input->get_post('reset_order')) {
            $this->session->unset_userdata('order');
        } else {
            // Get configs from query
            $order = array(
                'order_by' => $this->input->get_post('order_by'),
                'order_way' => $this->input->get_post('order_way'),
            );
            
            // Get configs from session
            if (empty($order['order_by']) || empty($order['order_way'])) {
                $order = $this->session->userdata('order');
            }
            
            if (empty($order['order_by']) || empty($order['order_way'])) {
                // Reset configs
                $this->session->unset_userdata('order');
            } else {
                // Enable configs
                $this->session->set_userdata('order', $order);
            }
        }
    }
    
	protected function initListing($model, $primaryKey, $table, $table_lang = false, $sql = NULL, $sqlCount = NULL, $joinFeature = array())
	{
        $this->load->model($model);
        $model = basename($model);
        $tableColumns     = $this->$model->getFieldsName();
        if ($table_lang) {
            $tableLangColumns = $this->$model->getLangFieldsName();
        } else {
            $tableLangColumns = array();
        }
        
        // Reset sort params and filter params
        $allColumns = array_merge($tableColumns, $tableLangColumns);
        $order = $this->session->userdata('order');
        $filter = $this->session->userdata('filter');
        
        $d['order_by']   = (isset($order['order_by'])    && in_array($order['order_by'], $allColumns))   ? $order['order_by']   : $primaryKey;
        $d['order_way']  = (isset($order['order_way'])   && in_array($order['order_way'], $allColumns))  ? $order['order_way']  : 'ASC';
        $d['filter_by']  = (isset($filter['filter_by'])  && in_array($filter['filter_by'], $allColumns)) ? $filter['filter_by'] : NULL;
        $d['filter_val'] = (isset($filter['filter_val']) && in_array($filter['filter_by'], $allColumns)) ? $filter['filter_val']: NULL;
        
        $this->session->set_userdata('order', array('order_by'=>$d['order_by'], 'order_way'=>$d['order_way']));
        if (empty($d['filter_by']) || empty($d['filter_by']))
        {
            $this->session->unset_userdata('filter');
        } else {
            $this->session->set_userdata('filter', array('filter_by'=>$d['filter_by'], 'filter_val'=>$d['filter_val']));
        }
        
        // Pagination settings
        // Nbr of items to be displayed per page
        $perPage     = $this->getConfig('perPage')  ? (int)$this->getConfig('perPage')  : 10;
        $showPage    = $this->getConfig('showPage') ? (int)$this->getConfig('showPage') : 5;
        
        // Setting up paggination
        $page = (int)$this->input->get_post('page');
        if ($page < 1) $page = 1;
        
        // Build the sql request for listing
        if (empty($sql) || empty($sqlCount)) {
            $request = $this->buildSqlRequest($model, $primaryKey, $table, $table_lang, $tableColumns, $tableLangColumns, $page, $perPage, $showPage, $joinFeature);
        } else {
            $request = array('sql'=>$sql, 'sqlCount'=>$sqlCount);
        }
        
        $d['q'] = $this->input->get_post('q');
        $d['items'] = $this->$model->exec($request['sql']);
        $d['total'] = $this->$model->exec($request['sqlCount']);
        if (!empty($d['total'][0]->count)) {
            $d['total'] = $d['total'][0]->count;
        } else {
            $d['total'] = 0;
        }
        
        // page, start, stop
        $d['currentPage'] = $page;
        $d['pagination']  = $this->getPaginationConfig($page, $d['total'], $perPage, $showPage);
        
        return $d;
	}
    
    protected function buildSqlRequest ($model, $primaryKey, $table, $table_lang, $tableColumns, $tableLangColumns, $page, $perPage, $showPage, $joinFeature = array())
    {
        // Filter by key word
        $d['q'] = $this->input->get_post('q');
        $condition = '';
        if (!empty($d['q'])) {
            $queries = explode(' ', $d['q']);
            foreach ($queries as $v) {
                // Default fields
                foreach ($tableColumns AS $field) {
                    if (is_numeric($v)) {
                        $condition .= '`'.$model.'`.`'.$field.'` = '. (int)$v .' OR ';
                    } else {
                        $condition .= '`'.$model.'`.`'.$field.'` LIKE \'%'. $v .'%\' OR ';
                    }
                }
                if ($table_lang) {
                    // Lang fields
                    foreach ($tableLangColumns AS $field) {
                        if (is_numeric($v)) {
                            $condition .= '`'.$model.'Lang`.`'.$field.'` = '. (int)$v .' OR ';
                        } else {
                            $condition .= '`'.$model.'Lang`.`'.$field.'` LIKE \'%'. $v .'%\' OR ';
                        }
                    }
                }
            }
            $condition = substr($condition, 0, (strlen($condition) - 4));
        }
        if (empty($condition)){
            $condition = '1';
        }
        
        // Filter by a value
        if ($this->session->userdata('filter')) {
            $filter = $this->session->userdata('filter');
            $condition       .= ' AND '. ($filter['filter_by'] == 'id' ? '`'.$model.'`.`'.$primaryKey.'`' : (in_array($filter['filter_by'], $tableColumns)?'`'.$model.'`.':(in_array($order['filter_by'], $tableLangColumns)?'`'.$model.'Lang`.':'')).'`'.$filter['filter_by'].'`').'=\''.$filter['filter_val'].'\'';
        }
        
        // Order by a field
        if ($this->session->userdata('order')) {
            $order = $this->session->userdata('order');
            $orderCond = ($order['order_by'] == 'id' ? '`'.$model.'`.`'.$primaryKey.'`' : (in_array($order['order_by'], $tableColumns)?'`'.$model.'`.':(in_array($order['order_by'], $tableLangColumns)?'`'.$model.'Lang`.':'')).'`'.$order['order_by'].'`') .' '. $order['order_way']; 
        } else {
            $orderCond = '`'.$model.'`.`'.$primaryKey.'` ASC';
        }
        
        // Manging join clause
        $selectJoin = '';
        $joinClause = '';
        foreach ($joinFeature AS $join) {
            if (empty($join['table']) || empty($join['onclause']))
                continue;
            
            if (!empty($join['select']))
                $selectJoin .= ','. $join['select'];
            
            $joinClause .= (empty($join['type']) ? 'LEFT JOIN' : $join['type']) .' '. $join['table'] .' ON ('. $join['onclause'] .')';
        }
        
        if (empty($sql)) {
            $sql = '
                SELECT `'.$model.'`.*'. ($table_lang ? ', `'.$model.'Lang`.*' : ''). $selectJoin .'
                FROM `'.$table.'` `'.$model.'`'. 
                ($table_lang ? ('LEFT JOIN `'.$table_lang.'` `'.$model.'Lang` ON (`'.$model.'`.`'.$primaryKey.'` = `'.$model.'Lang`.`'.$primaryKey.'` AND `'.$model.'Lang`.`lang` = \''. $this->session->userdata('lang') .'\')') : '') .
                $joinClause .'
                WHERE '. $condition .'
                ORDER BY '. $orderCond .'
                LIMIT '. ($perPage*($page-1)).','.$perPage .'
            ';
        }
        if (empty($sqlCount)) {
            $sqlCount = '
                SELECT COUNT(DISTINCT `'.$model.'`.`'.$primaryKey.'`) AS `count`
                FROM `'.$table.'` `'.$model.'`'. 
                ($table_lang ? ('LEFT JOIN `'.$table_lang.'` `'.$model.'Lang` ON (`'.$model.'`.`'.$primaryKey.'` = `'.$model.'Lang`.`'.$primaryKey.'` AND `'.$model.'Lang`.`lang` = \''. $this->session->userdata('lang') .'\')') : '') . 
                $joinClause .'
                WHERE '. $condition .'
            ';
        }
        return array('sql'=>$sql, 'sqlCount'=>$sqlCount);
    }
    
    protected function initValidation ($formConfig)
    {
        $config = array();
        foreach ($formConfig AS $kSect => $section) {
            if (!is_int($kSect)) continue;
            
            // Fields for each section
            if (is_array($section['input'])) {
                foreach ($section['input'] AS $input) {
                    if (empty($input['lang'])) {
                        $config[] = array(
                            'field'   => $input['name'], 
                            'label'   => rtrim($input['label'], ':'), 
                            'rules'   => $input['rules']
                        );
                    } else {
                        // For lang fields
                        foreach (NZ_Config::$languages  AS $lang => $language) {
                            $config[] = array(
                                'field'   => $input['name'].'_'.$lang, 
                                'label'   => rtrim($input['label'], ':'), 
                                'rules'   => $input['rules']
                            );
                        }
                    }
                }
            }
            
            if (is_array($section['tabs'])) {
                foreach ($section['tabs'] AS $kTab => $tab) {
                    if (!is_int($kTab)) continue;
                    
                    // Fields for each tabs
                    if (is_array($tab['input'])) {
                        foreach ($tab['input'] AS $input) {
                            if (empty($input['lang'])) {
                                $config[] = array(
                                    'field'   => $input['name'], 
                                    'label'   => rtrim($input['label'], ':'), 
                                    'rules'   => $input['rules']
                                );
                            } else {
                                // For lang fields
                                foreach (NZ_Config::$languages  AS $lang => $language) {
                                    $config[] = array(
                                        'field'   => $input['name'].'_'.$lang, 
                                        'label'   => rtrim($input['label'], ':'), 
                                        'rules'   => $input['rules']
                                    );
                                }
                            }
                        }
                    }
                }
            }
        }
        return $config;
    }
    
    protected function extractSubmittedValues ($formConfig)
    {
        $record = array();
        foreach ($formConfig AS $kSect => $section) {
            if (!is_int($kSect)) continue;
            
            // Fields for each section
            if (is_array($section['input'])) {
                foreach ($section['input'] AS $input) {
                    if (empty($input['lang'])) {
                        $record[$input['name']] = $this->input->get_post($input['name']);
                    } else {
                        // For lang fields
                        foreach (NZ_Config::$languages  AS $lang => $language) {
                            $record[$input['name']][$lang] = $this->input->get_post($input['name'].'_'.$lang);
                        }
                    }
                }
            }
            
            if (is_array($section['tabs'])) {
                foreach ($section['tabs'] AS $kTab => $tab) {
                    if (!is_int($kTab)) continue;
                    
                    // Fields for each tabs
                    if (is_array($tab['input'])) {
                        foreach ($tab['input'] AS $input) {
                            if (empty($input['lang'])) {
                                $record[$input['name']] = $this->input->get_post($input['name']);
                            } else {
                                // For lang fields
                                foreach (NZ_Config::$languages  AS $lang => $language) {
                                    $record[$input['name']][$lang] = $this->input->get_post($input['name'].'_'.$lang);
                                }
                            }
                        }
                    }
                }
            }
        }
        return $record;
    }
    
    /**
     * AbstractController::_remap()
     * 
     * Remap the name of controller methode. The name of all action should be prefixed by Action
     * 
     * @param mixed $method the default method name
     * @param mixed $params the parameters
     * @return 
     */
    public function _remap($method, $params = array())
    {
        $method = $method.'Action';
        if (method_exists($this, $method))
        {
            if (ENVIRONMENT == 'development') {
                $this->enableProfiler();
            } else {
                $this->disableProfiler();
            }
            $this->preProcess();
            $result = call_user_func_array(array($this, $method), $params);
            $this->postProcess();
            return $result;
        }/*
        debug($method);
        debug(get_class($this));
        debug(get_class_methods($this));
        die();*/
        show_404();
    }

	/**
	 * AbstractController::preProcess()
     * 
     * Executed before any action
	 * 
	 * @return void
	 */
	public function preProcess() {}
    
	/**
	 * AbstractController::postProcess()
     * 
     * Executed after any action
	 * 
	 * @return void
	 */
	public function postProcess() {}
    
    
    /**
     * AbstractController::enableProfiler()
     * 
     * Enabled profiler in application
     * 
     * @return void
     */
    public function enableProfiler() 
    {
        $sections = array(
            'benchmarks'         => TRUE, // Elapsed time of Benchmark points and total execution time
            'config'             => TRUE, // CodeIgniter Config variables
            'controller_info'    => TRUE, // The Controller class and method requested
            'get'                => TRUE, // Any GET data passed in the request
            'http_headers'       => TRUE, // The HTTP headers for the current request
            'memory_usage'       => TRUE, // Amount of memory consumed by the current request, in bytes
            'post'               => TRUE, // Any POST data passed in the request
            'queries'            => TRUE, // Listing of all database queries executed, including execution time
            'uri_string'         => TRUE, // The URI of the current request
            'query_toggle_count' => 25,   // The number of queries after which the query block will default to hidden.
        );
        
        $this->output->enable_profiler(TRUE);
        $this->output->set_profiler_sections($sections);
    }
    
	public function disableProfiler() 
    {
        $this->output->enable_profiler(FALSE);
    }


	/**
	 * AbstractController::l()
     * 
     * Used to translate a text. The text to be translated must be a string between ' and '. As $this->l('Hello world').
     * Things such as $this->l("Hello world"); or $string = "Hello world";$this->l($string); will not work.
	 * 
	 * @param mixed $string the text to be translated.
	 * @param mixed $iso_code
	 * @return
	 */
	public function l ($string, $iso_code = null)
    {
        // Get tu current language
		if (empty($iso_code)) $iso_code = $this->session->userdata('lang');
        
        // Get the file path relative by application root directory
		$debug = current(debug_backtrace()); 
        $class = basename($debug['file']);
        $path  = str_replace("\\", "/", dirname($debug['file']) );
        
        $times = 5;
        $basePath = substr(((BASEPATH == '/')?'':dirname(BASEPATH)).'/'.APPPATH, 0, strlen(((BASEPATH == '/')?'':dirname(BASEPATH)).'/'.APPPATH)-1);
        while ($path != $basePath && $times > 0) {
            $class = basename($path).'/'.$class;
            $path  = dirname($path);
            $times--;
        }
        
        return TranslateMetier::getTranslation($string, $class, $iso_code);
	}
    
    /**
     * AbstractController::getPaginationConfig()
     * 
     * Build pagination configuration
     * 
     * @param integer $currentPage the number of the current page
     * @param integer $total the total of items
     * @param integer $perPage the number of items per page
     * @param integer $showPage the number of page to be displayed in pagination
     * @return the configuration of pages for the pagination
     */
    protected function getPaginationConfig ($currentPage = 1, $total = 0, $perPage = 10, $showPage = 10) 
    { 
		$d = array();
        $d['page']  = ceil($total / $perPage);
		$d['start'] = ($currentPage - ceil($showPage / 2));
		$d['stop']  = ($currentPage + ceil($showPage / 2));
        
        // Ajust start
        if ($d['start'] <= 0) {
            $d['stop'] += abs($d['start'] + 1);
            $d['start'] = 1;
        }
        // Ajust stop
        if ($d['stop'] > $d['page']) {
            if ($d['start'] > 0) {
                $d['start'] -= ($d['stop'] - $d['page']);
                if ($d['start'] <= 0) $d['start'] = 1;
            }
            $d['stop'] = $d['page'];
        }
        
        return $d;
    }

    /**
     * AbstractController::renderMail()
     * 
     * Render a mail form the view and the mail layout, then send it.
     * 
     * @param mixed $params parameters to be sent to the view, the mail layout and params of the sender. 
     * @param string $view the name of the mail view to be used
     * @return true if the mail was sent successfully.
     */
    protected function renderMail ($params, $view = 'mail') 
    {
        // The target is required.
        if (empty($params['to'])) {
            return false;
        }
        
        // Render the mail contenant, depending on the associated view.
        $content_for_layout = $this->load->view('Templates/Mails/'.$view, $params, true);
        
        // The default name of the receiver of the mail
        if (!isset($params['receiver']))
            $params['receiver'] = '';
        
        // The deffault name of the sender
        if (!isset($params['fromName']))
            $params['fromName'] = $this->l('My WebSite');
        
        // The mail default sender
        if (!isset($params['from']))
            $params['from']     = $this->l('admin@technique.dev');
        
        // The mail default subject
        if (!isset($params['subject']))
            $params['subject']  = $this->l('My WebSite');
        // Adding a prefix
        $params['subject']      = '['. $this->l('Suject Prefix') .'] '.$params['subject'];
        
        // Render the template of all mail
        extract((array)$params);
        ob_start();
        require ((BASEPATH == '/')?'':dirname(BASEPATH)).'/'.APPPATH.'views/Templates/Layouts/MailLayout.php';
        $mail_contains = ob_get_clean();
        
        // Send the mail
        return $this->sendMail($params, $mail_contains);
    }
    
	/**
     * AbstractController::sendMail()
     * 
     * Send a mail
     * 
     * @param array $params Parameters of the mail
     * @param mixed $message The message to be sent
     * @return boolean True if the mail is successfully sent
     */
    protected function sendMail ($params, $message) 
    {
        $this->load->library('email');
        
        // Initialize and configure email
        $config['useragent'] = 'PHP'. phpversion();
        $config['charset']   = 'utf8';
        $config['mailtype']  = 'html';
        $config['wordwrap']  = TRUE;
        $this->email->initialize($config);
        
        $this->email->from($params['from'], $params['fromName']);
        $this->email->to($params['to']);
        
        if (!empty($params['replyTo'])) {
            if (empty($params['replyToName'])) $params['replyToName'] = $params['replyTo'];
            $this->email->reply_to($params['replyTo'], $params['replyToName']);
        }
        if (!empty($params['bcc']))
            $this->email->cc($params['cc']);
        if (!empty($params['bcc']))
            $this->email->bcc($params['bcc']);
        
        $this->email->subject($params['subject']);
        $this->email->message($message);
        $this->email->set_alt_message(strip_tags($message));
        
        if ($this->email->send()) {
            return true;
        } else {
            $this->session->set_flashdata('errorMessage', $this->email->print_debugger());
            return false;
        }
    }
    
    /**
     * AbstractController::uploadFile()
     * 
     * Upload a file, save it in a directory and save it in database if neccessary
     * 
     * @param string $name The name of the file input
     * @param array  $allowedExts The list of allowed extension
     * @param string $className The model that persiste the file (by saving it in database)
     * @param string $primaryKey The primary key of the database table of the object
     * @param array  $defaultValues The default values of the file instance to be saved in database
     * @return informations about the operation
     */
    public function uploadFile ($name, $allowedExts = array("gif", "jpeg", "jpg", "png", "pdf"), $className = null, $primaryKey = null, $defaultValues = null) {
        $data = array(
                    'error'    => false,
                    'errorMsg' => false,
                    $primaryKey=> NULL,
                    'filename' => NULL,
                    'size'     => NULL,
                    'type'     => NULL,
                    'url'      => NULL,
                );
        
        if (!empty($_FILES[$name])) {
        	$temp = explode(".", $_FILES[$name]["name"]);
        	$extension = strtolower(end($temp));
            
            // Allowed mime
            $allowedMime = array();
            self::initMimeTypeFull();
            foreach ($allowedExts as $ext) {
                if (isset(self::$mimeTypes[$ext])) {
                    $allowedMime = array_merge($allowedMime, self::$mimeTypes[$ext]);
                }
            }
            
        	if ((in_array($_FILES[$name]["type"], $allowedMime))
        		//&& ($_FILES[$name]["size"] < 20000)
        		&& in_array($extension, $allowedExts))
        	{
        		if ($_FILES[$name]["error"] > 0) {
        			$data['error']    = $_FILES[$name]["error"];
        			$data['errorMsg'] = $this->l('Upload failed.');
        		}
        		else {
                    $data['filename'] = md5(uniqid(rand(0, 9999))).'-'.$_FILES[$name]["name"];
                    $data['size']     = ($_FILES[$name]["size"] / 1024);
                    $data['type']     = $_FILES[$name]["type"];
        			if (file_exists(((BASEPATH == '/')?'':dirname(BASEPATH)).'/webroot/upload/'.$data['filename'])) {
        				$data['error']    = -2;
                        $data['errorMsg'] = $data['filename'] .' '. $this->l('already exists.');
        			}
        			else {
                        // Download the file in the right folder
                        move_uploaded_file($_FILES[$name]["tmp_name"], ((BASEPATH == '/')?'':dirname(BASEPATH)).'/webroot/upload/'.$data['filename']);
                        $data['url'] = base_url('upload/'.$data['filename']);
                        
                        // Save the file in data base
                        if ($className) {
                            $this->load->model($className);
                            // Get the base name
                            $className = basename($className);
                            
                            $entity = new stdClass();
                            $columns = $this->$className->getFieldsName();
                            if (is_object($defaultValues)) {
                                foreach (array_keys((array)$defaultValues) AS $field) {
                                    if (in_array($field, $columns)) {
                                        $entity->$field = $defaultValues->$field;
                                    }
                                }
                                if (in_array('filename', $columns)) {
                                    $entity->filename = $data['filename'];
                                }
                                if (in_array('date_add', $columns)) {
                                    $entity->date_add = @date('Y-m-d H:i:s');
                                }
                                if (in_array('date_upd', $columns)) {
                                    $entity->date_upd = @date('Y-m-d H:i:s');
                                }
                            }
                            
                            if (empty($primaryKey)) $primaryKey = 'id_'.strtolower($className);
                            // If necessary, we update a prevouis image
                            if (isset($defaultValues->$primaryKey) && $oldObject = $this->$className->getById((int)$defaultValues->$primaryKey)) {
                                if (file_exists(((BASEPATH == '/')?'':dirname(BASEPATH)).'/webroot/upload/'.$oldObject->filename)) {
                                    @unlink(((BASEPATH == '/')?'':dirname(BASEPATH)).'/webroot/upload/'.$oldObject->filename);
                                }
                                $entity->$primaryKey = $oldObject->$primaryKey;
                            }
                            if ($this->$className->save((array)$entity)) {
                                $data[$primaryKey] = $this->$className->$primaryKey;
                            } else {
                                $data['error']    = 0;
                                $data['errorMsg'] = $this->l('The uploaded item was not added in database.');
                            }
                        }
        			}
        		}
        	} elseif (empty($_FILES[$name]["name"])) {
                $data['error']    = 0;
                $data['errorMsg'] = $this->l('No file uploaded.');
        	} else {
                $data['error']    = -1;
                $data['errorMsg'] = $this->l('Invalid file.');
        	}
        }
        return $data;
    }
    
	/**
	 * AbstractController::download()
     * 
     * It is used to download an uploaded file
	 * 
	 * @param mixed $file The real file namse on hard disk
	 * @param mixed $filename The name to be send
	 */
	public static function download ($file, $filename)
	{
		/* Detect mime content type */
		$mimeType = false;
		if (function_exists('finfo_open'))
		{
			$finfo = @finfo_open(FILEINFO_MIME);
			$mimeType = @finfo_file($finfo, $file);
			@finfo_close($finfo);
		}
		else if (function_exists('mime_content_type'))
			$mimeType = @mime_content_type($file);
		else if (function_exists('exec'))
		{
			$mimeType = trim(@exec('file -b --mime-type '.escapeshellarg($file)));
			if (!$mimeType)
				$mimeType = trim(@exec('file --mime '.escapeshellarg($file)));
			if (!$mimeType)
				$mimeType = trim(@exec('file -bi '.escapeshellarg($file)));
		}

		if (empty($mimeType))
		{
			$bName = basename($filename);
			$bName = explode('.', $bName);
			$bName = strtolower($bName[count($bName) - 1]);

			$mimeTypes = self::initMimeTypeFull();

			if (isset($mimeTypes[$bName]))
				$mimeType = current($mimeTypes[$bName]);
			else
				$mimeType = 'application/octet-stream';
		}

		/* Set headers for download */
		header('Content-Transfer-Encoding: binary');
		header('Content-Type: '.$mimeType);
		header('Content-Length: '.filesize($file));
		header('Content-Disposition: attachment; filename="'.$filename.'"');
		ob_end_flush();
		$fp = fopen($file, 'rb');
		while (!feof($fp))
			echo fgets($fp, 16384);

		exit;
	}
    
    protected static function initMimeTypeFull () 
    {
        if (!empty(self::$mimeTypes)) {
            return self::$mimeTypes;
        }
        
        $array = array();
        $array['3dm'][] = 'x-world/x-3dmf';
        $array['3dmf'][] = 'x-world/x-3dmf';
        $array['a'][] = 'application/octet-stream';
        $array['aab'][] = 'application/x-authorware-bin';
        $array['aam'][] = 'application/x-authorware-map';
        $array['aas'][] = 'application/x-authorware-seg';
        $array['abc'][] = 'text/vnd.abc';
        $array['acgi'][] = 'text/html';
        $array['afl'][] = 'video/animaflex';
        $array['ai'][] = 'application/postscript';
        $array['aif'][] = 'audio/aiff';
        $array['aif'][] = 'audio/x-aiff';
        $array['aifc'][] = 'audio/aiff';
        $array['aifc'][] = 'audio/x-aiff';
        $array['aiff'][] = 'audio/aiff';
        $array['aiff'][] = 'audio/x-aiff';
        $array['aim'][] = 'application/x-aim';
        $array['aip'][] = 'text/x-audiosoft-intra';
        $array['ani'][] = 'application/x-navi-animation';
        $array['aos'][] = 'application/x-nokia-9000-communicator-add-on-software';
        $array['aps'][] = 'application/mime';
        $array['arc'][] = 'application/octet-stream';
        $array['arj'][] = 'application/arj';
        $array['arj'][] = 'application/octet-stream';
        $array['art'][] = 'image/x-jg';
        $array['asf'][] = 'video/x-ms-asf';
        $array['asm'][] = 'text/x-asm';
        $array['asp'][] = 'text/asp';
        $array['asx'][] = 'application/x-mplayer2';
        $array['asx'][] = 'video/x-ms-asf';
        $array['asx'][] = 'video/x-ms-asf-plugin';
        $array['au'][] = 'audio/basic';
        $array['au'][] = 'audio/x-au';
        $array['avi'][] = 'application/x-troff-msvideo';
        $array['avi'][] = 'video/avi';
        $array['avi'][] = 'video/msvideo';
        $array['avi'][] = 'video/x-msvideo';
        $array['avs'][] = 'video/avs-video';
        $array['bcpio'][] = 'application/x-bcpio';
        $array['bin'][] = 'application/mac-binary';
        $array['bin'][] = 'application/macbinary';
        $array['bin'][] = 'application/octet-stream';
        $array['bin'][] = 'application/x-binary';
        $array['bin'][] = 'application/x-macbinary';
        $array['bm'][] = 'image/bmp';
        $array['bmp'][] = 'image/bmp';
        $array['bmp'][] = 'image/x-windows-bmp';
        $array['boo'][] = 'application/book';
        $array['book'][] = 'application/book';
        $array['boz'][] = 'application/x-bzip2';
        $array['bsh'][] = 'application/x-bsh';
        $array['bz'][] = 'application/x-bzip';
        $array['bz2'][] = 'application/x-bzip2';
        $array['c'][] = 'text/plain';
        $array['c'][] = 'text/x-c';
        $array['c++'][] = 'text/plain';
        $array['cat'][] = 'application/vnd.ms-pki.seccat';
        $array['cc'][] = 'text/plain';
        $array['cc'][] = 'text/x-c';
        $array['ccad'][] = 'application/clariscad';
        $array['cco'][] = 'application/x-cocoa';
        $array['cdf'][] = 'application/cdf';
        $array['cdf'][] = 'application/x-cdf';
        $array['cdf'][] = 'application/x-netcdf';
        $array['cer'][] = 'application/pkix-cert';
        $array['cer'][] = 'application/x-x509-ca-cert';
        $array['cha'][] = 'application/x-chat';
        $array['chat'][] = 'application/x-chat';
        $array['class'][] = 'application/java';
        $array['class'][] = 'application/java-byte-code';
        $array['class'][] = 'application/x-java-class';
        $array['com'][] = 'application/octet-stream';
        $array['com'][] = 'text/plain';
        $array['conf'][] = 'text/plain';
        $array['cpio'][] = 'application/x-cpio';
        $array['cpp'][] = 'text/x-c';
        $array['cpt'][] = 'application/mac-compactpro';
        $array['cpt'][] = 'application/x-compactpro';
        $array['cpt'][] = 'application/x-cpt';
        $array['crl'][] = 'application/pkcs-crl';
        $array['crl'][] = 'application/pkix-crl';
        $array['crt'][] = 'application/pkix-cert';
        $array['crt'][] = 'application/x-x509-ca-cert';
        $array['crt'][] = 'application/x-x509-user-cert';
        $array['csh'][] = 'application/x-csh';
        $array['csh'][] = 'text/x-script.csh';
        $array['css'][] = 'application/x-pointplus';
        $array['css'][] = 'text/css';
        $array['cxx'][] = 'text/plain';
        $array['dcr'][] = 'application/x-director';
        $array['deepv'][] = 'application/x-deepv';
        $array['def'][] = 'text/plain';
        $array['der'][] = 'application/x-x509-ca-cert';
        $array['dif'][] = 'video/x-dv';
        $array['dir'][] = 'application/x-director';
        $array['dl'][] = 'video/dl';
        $array['dl'][] = 'video/x-dl';
        $array['doc'][] = 'application/msword';
        $array['dot'][] = 'application/msword';
        $array['dp'][] = 'application/commonground';
        $array['drw'][] = 'application/drafting';
        $array['dump'][] = 'application/octet-stream';
        $array['dv'][] = 'video/x-dv';
        $array['dvi'][] = 'application/x-dvi';
        $array['dwf'][] = 'drawing/x-dwf (old)';
        $array['dwf'][] = 'model/vnd.dwf';
        $array['dwg'][] = 'application/acad';
        $array['dwg'][] = 'image/vnd.dwg';
        $array['dwg'][] = 'image/x-dwg';
        $array['dxf'][] = 'application/dxf';
        $array['dxf'][] = 'image/vnd.dwg';
        $array['dxf'][] = 'image/x-dwg';
        $array['dxr'][] = 'application/x-director';
        $array['el'][] = 'text/x-script.elisp';
        $array['elc'][] = 'application/x-bytecode.elisp (compiled elisp)';
        $array['elc'][] = 'application/x-elc';
        $array['env'][] = 'application/x-envoy';
        $array['eps'][] = 'application/postscript';
        $array['es'][] = 'application/x-esrehber';
        $array['etx'][] = 'text/x-setext';
        $array['evy'][] = 'application/envoy';
        $array['evy'][] = 'application/x-envoy';
        $array['exe'][] = 'application/octet-stream';
        $array['f'][] = 'text/plain';
        $array['f'][] = 'text/x-fortran';
        $array['f77'][] = 'text/x-fortran';
        $array['f90'][] = 'text/plain';
        $array['f90'][] = 'text/x-fortran';
        $array['fdf'][] = 'application/vnd.fdf';
        $array['fif'][] = 'application/fractals';
        $array['fif'][] = 'image/fif';
        $array['fli'][] = 'video/fli';
        $array['fli'][] = 'video/x-fli';
        $array['flo'][] = 'image/florian';
        $array['flx'][] = 'text/vnd.fmi.flexstor';
        $array['fmf'][] = 'video/x-atomic3d-feature';
        $array['for'][] = 'text/plain';
        $array['for'][] = 'text/x-fortran';
        $array['fpx'][] = 'image/vnd.fpx';
        $array['fpx'][] = 'image/vnd.net-fpx';
        $array['frl'][] = 'application/freeloader';
        $array['funk'][] = 'audio/make';
        $array['g'][] = 'text/plain';
        $array['g3'][] = 'image/g3fax';
        $array['gif'][] = 'image/gif';
        $array['gl'][] = 'video/gl';
        $array['gl'][] = 'video/x-gl';
        $array['gsd'][] = 'audio/x-gsm';
        $array['gsm'][] = 'audio/x-gsm';
        $array['gsp'][] = 'application/x-gsp';
        $array['gss'][] = 'application/x-gss';
        $array['gtar'][] = 'application/x-gtar';
        $array['gz'][] = 'application/x-compressed';
        $array['gz'][] = 'application/x-gzip';
        $array['gzip'][] = 'application/x-gzip';
        $array['gzip'][] = 'multipart/x-gzip';
        $array['h'][] = 'text/plain';
        $array['h'][] = 'text/x-h';
        $array['hdf'][] = 'application/x-hdf';
        $array['help'][] = 'application/x-helpfile';
        $array['hgl'][] = 'application/vnd.hp-hpgl';
        $array['hh'][] = 'text/plain';
        $array['hh'][] = 'text/x-h';
        $array['hlb'][] = 'text/x-script';
        $array['hlp'][] = 'application/hlp';
        $array['hlp'][] = 'application/x-helpfile';
        $array['hlp'][] = 'application/x-winhelp';
        $array['hpg'][] = 'application/vnd.hp-hpgl';
        $array['hpgl'][] = 'application/vnd.hp-hpgl';
        $array['hqx'][] = 'application/binhex';
        $array['hqx'][] = 'application/binhex4';
        $array['hqx'][] = 'application/mac-binhex';
        $array['hqx'][] = 'application/mac-binhex40';
        $array['hqx'][] = 'application/x-binhex40';
        $array['hqx'][] = 'application/x-mac-binhex40';
        $array['hta'][] = 'application/hta';
        $array['htc'][] = 'text/x-component';
        $array['htm'][] = 'text/html';
        $array['html'][] = 'text/html';
        $array['htmls'][] = 'text/html';
        $array['htt'][] = 'text/webviewhtml';
        $array['htx'][] = 'text/html';
        $array['ice'][] = 'x-conference/x-cooltalk';
        $array['ico'][] = 'image/x-icon';
        $array['idc'][] = 'text/plain';
        $array['ief'][] = 'image/ief';
        $array['iefs'][] = 'image/ief';
        $array['iges'][] = 'application/iges';
        $array['iges'][] = 'model/iges';
        $array['igs'][] = 'application/iges';
        $array['igs'][] = 'model/iges';
        $array['ima'][] = 'application/x-ima';
        $array['imap'][] = 'application/x-httpd-imap';
        $array['inf'][] = 'application/inf';
        $array['ins'][] = 'application/x-internett-signup';
        $array['ip'][] = 'application/x-ip2';
        $array['isu'][] = 'video/x-isvideo';
        $array['it'][] = 'audio/it';
        $array['iv'][] = 'application/x-inventor';
        $array['ivr'][] = 'i-world/i-vrml';
        $array['ivy'][] = 'application/x-livescreen';
        $array['jam'][] = 'audio/x-jam';
        $array['jav'][] = 'text/plain';
        $array['jav'][] = 'text/x-java-source';
        $array['java'][] = 'text/plain';
        $array['java'][] = 'text/x-java-source';
        $array['jcm'][] = 'application/x-java-commerce';
        $array['jfif'][] = 'image/jpeg';
        $array['jfif'][] = 'image/pjpeg';
        $array['jfif-tbnl'][] = 'image/jpeg';
        $array['jpe'][] = 'image/jpeg';
        $array['jpe'][] = 'image/pjpeg';
        $array['jpeg'][] = 'image/jpeg';
        $array['jpeg'][] = 'image/pjpeg';
        $array['jpg'][] = 'image/jpeg';
        $array['jpg'][] = 'image/pjpeg';
        $array['jps'][] = 'image/x-jps';
        $array['js'][] = 'application/x-javascript';
        $array['js'][] = 'application/javascript';
        $array['js'][] = 'application/ecmascript';
        $array['js'][] = 'text/javascript';
        $array['js'][] = 'text/ecmascript';
        $array['jut'][] = 'image/jutvision';
        $array['kar'][] = 'audio/midi';
        $array['kar'][] = 'music/x-karaoke';
        $array['ksh'][] = 'application/x-ksh';
        $array['ksh'][] = 'text/x-script.ksh';
        $array['la'][] = 'audio/nspaudio';
        $array['la'][] = 'audio/x-nspaudio';
        $array['lam'][] = 'audio/x-liveaudio';
        $array['latex'][] = 'application/x-latex';
        $array['lha'][] = 'application/lha';
        $array['lha'][] = 'application/octet-stream';
        $array['lha'][] = 'application/x-lha';
        $array['lhx'][] = 'application/octet-stream';
        $array['list'][] = 'text/plain';
        $array['lma'][] = 'audio/nspaudio';
        $array['lma'][] = 'audio/x-nspaudio';
        $array['log'][] = 'text/plain';
        $array['lsp'][] = 'application/x-lisp';
        $array['lsp'][] = 'text/x-script.lisp';
        $array['lst'][] = 'text/plain';
        $array['lsx'][] = 'text/x-la-asf';
        $array['ltx'][] = 'application/x-latex';
        $array['lzh'][] = 'application/octet-stream';
        $array['lzh'][] = 'application/x-lzh';
        $array['lzx'][] = 'application/lzx';
        $array['lzx'][] = 'application/octet-stream';
        $array['lzx'][] = 'application/x-lzx';
        $array['m'][] = 'text/plain';
        $array['m'][] = 'text/x-m';
        $array['m1v'][] = 'video/mpeg';
        $array['m2a'][] = 'audio/mpeg';
        $array['m2v'][] = 'video/mpeg';
        $array['m3u'][] = 'audio/x-mpequrl';
        $array['man'][] = 'application/x-troff-man';
        $array['map'][] = 'application/x-navimap';
        $array['mar'][] = 'text/plain';
        $array['mbd'][] = 'application/mbedlet';
        $array['mc$'][] = 'application/x-magic-cap-package-1.0';
        $array['mcd'][] = 'application/mcad';
        $array['mcd'][] = 'application/x-mathcad';
        $array['mcf'][] = 'image/vasa';
        $array['mcf'][] = 'text/mcf';
        $array['mcp'][] = 'application/netmc';
        $array['me'][] = 'application/x-troff-me';
        $array['mht'][] = 'message/rfc822';
        $array['mhtml'][] = 'message/rfc822';
        $array['mid'][] = 'application/x-midi';
        $array['mid'][] = 'audio/midi';
        $array['mid'][] = 'audio/x-mid';
        $array['mid'][] = 'audio/x-midi';
        $array['mid'][] = 'music/crescendo';
        $array['mid'][] = 'x-music/x-midi';
        $array['midi'][] = 'application/x-midi';
        $array['midi'][] = 'audio/midi';
        $array['midi'][] = 'audio/x-mid';
        $array['midi'][] = 'audio/x-midi';
        $array['midi'][] = 'music/crescendo';
        $array['midi'][] = 'x-music/x-midi';
        $array['mif'][] = 'application/x-frame';
        $array['mif'][] = 'application/x-mif';
        $array['mime'][] = 'message/rfc822';
        $array['mime'][] = 'www/mime';
        $array['mjf'][] = 'audio/x-vnd.audioexplosion.mjuicemediafile';
        $array['mjpg'][] = 'video/x-motion-jpeg';
        $array['mm'][] = 'application/base64';
        $array['mm'][] = 'application/x-meme';
        $array['mme'][] = 'application/base64';
        $array['mod'][] = 'audio/mod';
        $array['mod'][] = 'audio/x-mod';
        $array['moov'][] = 'video/quicktime';
        $array['mov'][] = 'video/quicktime';
        $array['movie'][] = 'video/x-sgi-movie';
        $array['mp2'][] = 'audio/mpeg';
        $array['mp2'][] = 'audio/x-mpeg';
        $array['mp2'][] = 'video/mpeg';
        $array['mp2'][] = 'video/x-mpeg';
        $array['mp2'][] = 'video/x-mpeq2a';
        $array['mp3'][] = 'audio/mpeg3';
        $array['mp3'][] = 'audio/x-mpeg-3';
        $array['mp3'][] = 'video/mpeg';
        $array['mp3'][] = 'video/x-mpeg';
        $array['mpa'][] = 'audio/mpeg';
        $array['mpa'][] = 'video/mpeg';
        $array['mpc'][] = 'application/x-project';
        $array['mpe'][] = 'video/mpeg';
        $array['mpeg'][] = 'video/mpeg';
        $array['mpg'][] = 'audio/mpeg';
        $array['mpg'][] = 'video/mpeg';
        $array['mpga'][] = 'audio/mpeg';
        $array['mpp'][] = 'application/vnd.ms-project';
        $array['mpt'][] = 'application/x-project';
        $array['mpv'][] = 'application/x-project';
        $array['mpx'][] = 'application/x-project';
        $array['mrc'][] = 'application/marc';
        $array['ms'][] = 'application/x-troff-ms';
        $array['mv'][] = 'video/x-sgi-movie';
        $array['my'][] = 'audio/make';
        $array['mzz'][] = 'application/x-vnd.audioexplosion.mzz';
        $array['nap'][] = 'image/naplps';
        $array['naplps'][] = 'image/naplps';
        $array['nc'][] = 'application/x-netcdf';
        $array['ncm'][] = 'application/vnd.nokia.configuration-message';
        $array['nif'][] = 'image/x-niff';
        $array['niff'][] = 'image/x-niff';
        $array['nix'][] = 'application/x-mix-transfer';
        $array['nsc'][] = 'application/x-conference';
        $array['nvd'][] = 'application/x-navidoc';
        $array['o'][] = 'application/octet-stream';
        $array['oda'][] = 'application/oda';
        $array['omc'][] = 'application/x-omc';
        $array['omcd'][] = 'application/x-omcdatamaker';
        $array['omcr'][] = 'application/x-omcregerator';
        $array['p'][] = 'text/x-pascal';
        $array['p10'][] = 'application/pkcs10';
        $array['p10'][] = 'application/x-pkcs10';
        $array['p12'][] = 'application/pkcs-12';
        $array['p12'][] = 'application/x-pkcs12';
        $array['p7a'][] = 'application/x-pkcs7-signature';
        $array['p7c'][] = 'application/pkcs7-mime';
        $array['p7c'][] = 'application/x-pkcs7-mime';
        $array['p7m'][] = 'application/pkcs7-mime';
        $array['p7m'][] = 'application/x-pkcs7-mime';
        $array['p7r'][] = 'application/x-pkcs7-certreqresp';
        $array['p7s'][] = 'application/pkcs7-signature';
        $array['part'][] = 'application/pro_eng';
        $array['pas'][] = 'text/pascal';
        $array['pbm'][] = 'image/x-portable-bitmap';
        $array['pcl'][] = 'application/vnd.hp-pcl';
        $array['pcl'][] = 'application/x-pcl';
        $array['pct'][] = 'image/x-pict';
        $array['pcx'][] = 'image/x-pcx';
        $array['pdb'][] = 'chemical/x-pdb';
        $array['pdf'][] = 'application/pdf';
        $array['pfunk'][] = 'audio/make';
        $array['pfunk'][] = 'audio/make.my.funk';
        $array['pgm'][] = 'image/x-portable-graymap';
        $array['pgm'][] = 'image/x-portable-greymap';
        $array['pic'][] = 'image/pict';
        $array['pict'][] = 'image/pict';
        $array['pkg'][] = 'application/x-newton-compatible-pkg';
        $array['pko'][] = 'application/vnd.ms-pki.pko';
        $array['pl'][] = 'text/plain';
        $array['pl'][] = 'text/x-script.perl';
        $array['plx'][] = 'application/x-pixclscript';
        $array['pm'][] = 'image/x-xpixmap';
        $array['pm'][] = 'text/x-script.perl-module';
        $array['pm4'][] = 'application/x-pagemaker';
        $array['pm5'][] = 'application/x-pagemaker';
        $array['png'][] = 'image/png';
        $array['pnm'][] = 'application/x-portable-anymap';
        $array['pnm'][] = 'image/x-portable-anymap';
        $array['pot'][] = 'application/mspowerpoint';
        $array['pot'][] = 'application/vnd.ms-powerpoint';
        $array['pov'][] = 'model/x-pov';
        $array['ppa'][] = 'application/vnd.ms-powerpoint';
        $array['ppm'][] = 'image/x-portable-pixmap';
        $array['pps'][] = 'application/mspowerpoint';
        $array['pps'][] = 'application/vnd.ms-powerpoint';
        $array['ppt'][] = 'application/mspowerpoint';
        $array['ppt'][] = 'application/powerpoint';
        $array['ppt'][] = 'application/vnd.ms-powerpoint';
        $array['ppt'][] = 'application/x-mspowerpoint';
        $array['ppz'][] = 'application/mspowerpoint';
        $array['pre'][] = 'application/x-freelance';
        $array['prt'][] = 'application/pro_eng';
        $array['ps'][] = 'application/postscript';
        $array['psd'][] = 'application/octet-stream';
        $array['pvu'][] = 'paleovu/x-pv';
        $array['pwz'][] = 'application/vnd.ms-powerpoint';
        $array['py'][] = 'text/x-script.phyton';
        $array['pyc'][] = 'applicaiton/x-bytecode.python';
        $array['qcp'][] = 'audio/vnd.qcelp';
        $array['qd3'][] = 'x-world/x-3dmf';
        $array['qd3d'][] = 'x-world/x-3dmf';
        $array['qif'][] = 'image/x-quicktime';
        $array['qt'][] = 'video/quicktime';
        $array['qtc'][] = 'video/x-qtc';
        $array['qti'][] = 'image/x-quicktime';
        $array['qtif'][] = 'image/x-quicktime';
        $array['ra'][] = 'audio/x-pn-realaudio';
        $array['ra'][] = 'audio/x-pn-realaudio-plugin';
        $array['ra'][] = 'audio/x-realaudio';
        $array['ram'][] = 'audio/x-pn-realaudio';
        $array['ras'][] = 'application/x-cmu-raster';
        $array['ras'][] = 'image/cmu-raster';
        $array['ras'][] = 'image/x-cmu-raster';
        $array['rast'][] = 'image/cmu-raster';
        $array['rexx'][] = 'text/x-script.rexx';
        $array['rf'][] = 'image/vnd.rn-realflash';
        $array['rgb'][] = 'image/x-rgb';
        $array['rm'][] = 'application/vnd.rn-realmedia';
        $array['rm'][] = 'audio/x-pn-realaudio';
        $array['rmi'][] = 'audio/mid';
        $array['rmm'][] = 'audio/x-pn-realaudio';
        $array['rmp'][] = 'audio/x-pn-realaudio';
        $array['rmp'][] = 'audio/x-pn-realaudio-plugin';
        $array['rng'][] = 'application/ringing-tones';
        $array['rng'][] = 'application/vnd.nokia.ringing-tone';
        $array['rnx'][] = 'application/vnd.rn-realplayer';
        $array['roff'][] = 'application/x-troff';
        $array['rp'][] = 'image/vnd.rn-realpix';
        $array['rpm'][] = 'audio/x-pn-realaudio-plugin';
        $array['rt'][] = 'text/richtext';
        $array['rt'][] = 'text/vnd.rn-realtext';
        $array['rtf'][] = 'application/rtf';
        $array['rtf'][] = 'application/x-rtf';
        $array['rtf'][] = 'text/richtext';
        $array['rtx'][] = 'application/rtf';
        $array['rtx'][] = 'text/richtext';
        $array['rv'][] = 'video/vnd.rn-realvideo';
        $array['s'][] = 'text/x-asm';
        $array['s3m'][] = 'audio/s3m';
        $array['saveme'][] = 'application/octet-stream';
        $array['sbk'][] = 'application/x-tbook';
        $array['scm'][] = 'application/x-lotusscreencam';
        $array['scm'][] = 'text/x-script.guile';
        $array['scm'][] = 'text/x-script.scheme';
        $array['scm'][] = 'video/x-scm';
        $array['sdml'][] = 'text/plain';
        $array['sdp'][] = 'application/sdp';
        $array['sdp'][] = 'application/x-sdp';
        $array['sdr'][] = 'application/sounder';
        $array['sea'][] = 'application/sea';
        $array['sea'][] = 'application/x-sea';
        $array['set'][] = 'application/set';
        $array['sgm'][] = 'text/sgml';
        $array['sgm'][] = 'text/x-sgml';
        $array['sgml'][] = 'text/sgml';
        $array['sgml'][] = 'text/x-sgml';
        $array['sh'][] = 'application/x-bsh';
        $array['sh'][] = 'application/x-sh';
        $array['sh'][] = 'application/x-shar';
        $array['sh'][] = 'text/x-script.sh';
        $array['shar'][] = 'application/x-bsh';
        $array['shar'][] = 'application/x-shar';
        $array['shtml'][] = 'text/html';
        $array['shtml'][] = 'text/x-server-parsed-html';
        $array['sid'][] = 'audio/x-psid';
        $array['sit'][] = 'application/x-sit';
        $array['sit'][] = 'application/x-stuffit';
        $array['skd'][] = 'application/x-koan';
        $array['skm'][] = 'application/x-koan';
        $array['skp'][] = 'application/x-koan';
        $array['skt'][] = 'application/x-koan';
        $array['sl'][] = 'application/x-seelogo';
        $array['smi'][] = 'application/smil';
        $array['smil'][] = 'application/smil';
        $array['snd'][] = 'audio/basic';
        $array['snd'][] = 'audio/x-adpcm';
        $array['sol'][] = 'application/solids';
        $array['spc'][] = 'application/x-pkcs7-certificates';
        $array['spc'][] = 'text/x-speech';
        $array['spl'][] = 'application/futuresplash';
        $array['spr'][] = 'application/x-sprite';
        $array['sprite'][] = 'application/x-sprite';
        $array['src'][] = 'application/x-wais-source';
        $array['ssi'][] = 'text/x-server-parsed-html';
        $array['ssm'][] = 'application/streamingmedia';
        $array['sst'][] = 'application/vnd.ms-pki.certstore';
        $array['step'][] = 'application/step';
        $array['stl'][] = 'application/sla';
        $array['stl'][] = 'application/vnd.ms-pki.stl';
        $array['stl'][] = 'application/x-navistyle';
        $array['stp'][] = 'application/step';
        $array['sv4cpio'][] = 'application/x-sv4cpio';
        $array['sv4crc'][] = 'application/x-sv4crc';
        $array['svf'][] = 'image/vnd.dwg';
        $array['svf'][] = 'image/x-dwg';
        $array['svr'][] = 'application/x-world';
        $array['svr'][] = 'x-world/x-svr';
        $array['swf'][] = 'application/x-shockwave-flash';
        $array['t'][] = 'application/x-troff';
        $array['talk'][] = 'text/x-speech';
        $array['tar'][] = 'application/x-tar';
        $array['tbk'][] = 'application/toolbook';
        $array['tbk'][] = 'application/x-tbook';
        $array['tcl'][] = 'application/x-tcl';
        $array['tcl'][] = 'text/x-script.tcl';
        $array['tcsh'][] = 'text/x-script.tcsh';
        $array['tex'][] = 'application/x-tex';
        $array['texi'][] = 'application/x-texinfo';
        $array['texinfo'][] = 'application/x-texinfo';
        $array['text'][] = 'application/plain';
        $array['text'][] = 'text/plain';
        $array['tgz'][] = 'application/gnutar';
        $array['tgz'][] = 'application/x-compressed';
        $array['tif'][] = 'image/tiff';
        $array['tif'][] = 'image/x-tiff';
        $array['tiff'][] = 'image/tiff';
        $array['tiff'][] = 'image/x-tiff';
        $array['tr'][] = 'application/x-troff';
        $array['tsi'][] = 'audio/tsp-audio';
        $array['tsp'][] = 'application/dsptype';
        $array['tsp'][] = 'audio/tsplayer';
        $array['tsv'][] = 'text/tab-separated-values';
        $array['turbot'][] = 'image/florian';
        $array['txt'][] = 'text/plain';
        $array['uil'][] = 'text/x-uil';
        $array['uni'][] = 'text/uri-list';
        $array['unis'][] = 'text/uri-list';
        $array['unv'][] = 'application/i-deas';
        $array['uri'][] = 'text/uri-list';
        $array['uris'][] = 'text/uri-list';
        $array['ustar'][] = 'application/x-ustar';
        $array['ustar'][] = 'multipart/x-ustar';
        $array['uu'][] = 'application/octet-stream';
        $array['uu'][] = 'text/x-uuencode';
        $array['uue'][] = 'text/x-uuencode';
        $array['vcd'][] = 'application/x-cdlink';
        $array['vcs'][] = 'text/x-vcalendar';
        $array['vda'][] = 'application/vda';
        $array['vdo'][] = 'video/vdo';
        $array['vew'][] = 'application/groupwise';
        $array['viv'][] = 'video/vivo';
        $array['viv'][] = 'video/vnd.vivo';
        $array['vivo'][] = 'video/vivo';
        $array['vivo'][] = 'video/vnd.vivo';
        $array['vmd'][] = 'application/vocaltec-media-desc';
        $array['vmf'][] = 'application/vocaltec-media-file';
        $array['voc'][] = 'audio/voc';
        $array['voc'][] = 'audio/x-voc';
        $array['vos'][] = 'video/vosaic';
        $array['vox'][] = 'audio/voxware';
        $array['vqe'][] = 'audio/x-twinvq-plugin';
        $array['vqf'][] = 'audio/x-twinvq';
        $array['vql'][] = 'audio/x-twinvq-plugin';
        $array['vrml'][] = 'application/x-vrml';
        $array['vrml'][] = 'model/vrml';
        $array['vrml'][] = 'x-world/x-vrml';
        $array['vrt'][] = 'x-world/x-vrt';
        $array['vsd'][] = 'application/x-visio';
        $array['vst'][] = 'application/x-visio';
        $array['vsw'][] = 'application/x-visio';
        $array['w60'][] = 'application/wordperfect6.0';
        $array['w61'][] = 'application/wordperfect6.1';
        $array['w6w'][] = 'application/msword';
        $array['wav'][] = 'audio/wav';
        $array['wav'][] = 'audio/x-wav';
        $array['wb1'][] = 'application/x-qpro';
        $array['wbmp'][] = 'image/vnd.wap.wbmp';
        $array['web'][] = 'application/vnd.xara';
        $array['wiz'][] = 'application/msword';
        $array['wk1'][] = 'application/x-123';
        $array['wmf'][] = 'windows/metafile';
        $array['wml'][] = 'text/vnd.wap.wml';
        $array['wmlc'][] = 'application/vnd.wap.wmlc';
        $array['wmls'][] = 'text/vnd.wap.wmlscript';
        $array['wmlsc'][] = 'application/vnd.wap.wmlscriptc';
        $array['word'][] = 'application/msword';
        $array['wp'][] = 'application/wordperfect';
        $array['wp5'][] = 'application/wordperfect';
        $array['wp5'][] = 'application/wordperfect6.0';
        $array['wp6'][] = 'application/wordperfect';
        $array['wpd'][] = 'application/wordperfect';
        $array['wpd'][] = 'application/x-wpwin';
        $array['wq1'][] = 'application/x-lotus';
        $array['wri'][] = 'application/mswrite';
        $array['wri'][] = 'application/x-wri';
        $array['wrl'][] = 'application/x-world';
        $array['wrl'][] = 'model/vrml';
        $array['wrl'][] = 'x-world/x-vrml';
        $array['wrz'][] = 'model/vrml';
        $array['wrz'][] = 'x-world/x-vrml';
        $array['wsc'][] = 'text/scriplet';
        $array['wsrc'][] = 'application/x-wais-source';
        $array['wtk'][] = 'application/x-wintalk';
        $array['xbm'][] = 'image/x-xbitmap';
        $array['xbm'][] = 'image/x-xbm';
        $array['xbm'][] = 'image/xbm';
        $array['xdr'][] = 'video/x-amt-demorun';
        $array['xgz'][] = 'xgl/drawing';
        $array['xif'][] = 'image/vnd.xiff';
        $array['xl'][] = 'application/excel';
        $array['xla'][] = 'application/excel';
        $array['xla'][] = 'application/x-excel';
        $array['xla'][] = 'application/x-msexcel';
        $array['xlb'][] = 'application/excel';
        $array['xlb'][] = 'application/vnd.ms-excel';
        $array['xlb'][] = 'application/x-excel';
        $array['xlc'][] = 'application/excel';
        $array['xlc'][] = 'application/vnd.ms-excel';
        $array['xlc'][] = 'application/x-excel';
        $array['xld'][] = 'application/excel';
        $array['xld'][] = 'application/x-excel';
        $array['xlk'][] = 'application/excel';
        $array['xlk'][] = 'application/x-excel';
        $array['xll'][] = 'application/excel';
        $array['xll'][] = 'application/vnd.ms-excel';
        $array['xll'][] = 'application/x-excel';
        $array['xlm'][] = 'application/excel';
        $array['xlm'][] = 'application/vnd.ms-excel';
        $array['xlm'][] = 'application/x-excel';
        $array['xls'][] = 'application/excel';
        $array['xls'][] = 'application/vnd.ms-excel';
        $array['xls'][] = 'application/x-excel';
        $array['xls'][] = 'application/x-msexcel';
        $array['xlt'][] = 'application/excel';
        $array['xlt'][] = 'application/x-excel';
        $array['xlv'][] = 'application/excel';
        $array['xlv'][] = 'application/x-excel';
        $array['xlw'][] = 'application/excel';
        $array['xlw'][] = 'application/vnd.ms-excel';
        $array['xlw'][] = 'application/x-excel';
        $array['xlw'][] = 'application/x-msexcel';
        $array['xm'][] = 'audio/xm';
        $array['xml'][] = 'application/xml';
        $array['xml'][] = 'text/xml';
        $array['xmz'][] = 'xgl/movie';
        $array['xpix'][] = 'application/x-vnd.ls-xpix';
        $array['xpm'][] = 'image/x-xpixmap';
        $array['xpm'][] = 'image/xpm';
        $array['x-png'][] = 'image/png';
        $array['xsr'][] = 'video/x-amt-showrun';
        $array['xwd'][] = 'image/x-xwd';
        $array['xwd'][] = 'image/x-xwindowdump';
        $array['xyz'][] = 'chemical/x-pdb';
        $array['z'][] = 'application/x-compress';
        $array['z'][] = 'application/x-compressed';
        $array['zip'][] = 'application/x-compressed';
        $array['zip'][] = 'application/x-zip-compressed';
        $array['zip'][] = 'application/zip';
        $array['zip'][] = 'multipart/x-zip';
        $array['zoo'][] = 'application/octet-stream';
        $array['zsh'][] = 'text/x-script.zsh';
        
        // Added by me
        $array['zip'][] = 'application/octet-stream';
        
        self::$mimeTypes = $array;
        return self::$mimeTypes;
    }
}

